﻿<xsl:stylesheet xmlns:x="http://www.w3.org/2001/XMLSchema"
     version="1.0" xmlns:str="http://exslt.org/strings" xmlns:c="http://exslt.org/common"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    exclude-result-prefixes="str c x xsl">

	<xsl:output omit-xml-declaration="yes"   />

	<xsl:variable name="alphabet">ABCDEFGHIJKLMNOPQRSTUVWXYZ</xsl:variable>

	<xsl:key name="matchedTitles" match="//rows/row/AtoZTitle1[. != ''] | //rows/row/AtoZTitle2[. != '']" use="substring(., 1, 1)"/>

	<xsl:template match="/">
		<xsl:apply-templates select="rows"/>
	</xsl:template>

	<xsl:template match="rows">

		<xsl:call-template name="recurseAlphabet">
			<xsl:with-param name="currentPosition" select="number(1)"/>
		</xsl:call-template>

	</xsl:template>

	<xsl:template name="recurseAlphabet">
		<xsl:param name="currentPosition"/>

		<xsl:call-template name="letter">
			<xsl:with-param name="currentLetter">
				<xsl:value-of select="substring($alphabet, $currentPosition, 1)"/>
			</xsl:with-param>
		</xsl:call-template>

		<xsl:if test="$currentPosition != 26">
			<xsl:call-template name="recurseAlphabet">
				<xsl:with-param name="currentPosition" select="$currentPosition + 1"/>
			</xsl:call-template>
		</xsl:if>

	</xsl:template>

	<xsl:template name="letter">
		<xsl:param name="currentLetter"/>
		<xsl:variable name="titles" select="key('matchedTitles', $currentLetter)"/>

		<xsl:if test="count($titles) &gt; 0">
			<h2 class="atoz">
				<xsl:value-of select="$currentLetter"/>
			</h2>

			<xsl:apply-templates select="$titles">
				<xsl:sort select="."/>
			</xsl:apply-templates>
		</xsl:if>
	</xsl:template>

	<xsl:template match="AtoZTitle1 | AtoZTitle2">

		<li>
			<a href="/{substring-after(../FileRef, '#')}">
				<xsl:value-of select="."/>
				<br/>
			</a>
			<br/>
		</li>

	</xsl:template>


</xsl:stylesheet>

